package com.kotlin.notes.coroutine

import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.lang.Thread.sleep
import kotlin.system.measureTimeMillis

class CoroutineDemo {


    fun doSomething() {
        for (i in 0..5) {
            println(i)
            sleep(1000)
        }

        println("doSomething done")
    }


    suspend fun suspendDoSomething() {
        for (i in 0..5) {
            println(i)
            delay(1000)
        }
    }


    suspend fun doSomethingA(): Int {
        delay(1000L) // pretend we are doing something useful here
        return 10
    }

    suspend fun doSomethingB(): Int {
        delay(1000L) // pretend we are doing something useful here, too
        return 10
    }


}

fun main() = runBlocking {
    val d = CoroutineDemo()
//    run {
//        val time = measureTimeMillis {
//            val a = d.doSomethingA()
//            val b = d.doSomethingB()
//            println("The answer is ${a + b}")
//        }
//        println("Completed in $time ms")
//    }

    run {
        val time = measureTimeMillis {
            val a = async { d.doSomethingA() }
            val b = async { d.doSomethingB() }
            println("The answer is ${a.await() + b.await()}")
        }
        println("Completed in $time ms")
    }


//    d.doSomething()
//
//    val job = GlobalScope.launch {
//        d.suspendDoSomething()
//    }
//
//    println("suspendDoSomething done?")
//
//    job.join()
//
//    println("suspendDoSomething done!")

}


// https://kotlinlang.org/docs/reference/coroutines.html